﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace IOP.AspNetCore.Extension
{
    /// <summary>
    /// API服务扩展接口
    /// </summary>
    public static class APIServiceExtension
    {
        /// <summary>
        /// 添加API服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddAPIServices(this IServiceCollection services)
        {
            Assembly assembly = Assembly.GetEntryAssembly();
            services = AddAPIServices(services, assembly);
            return services;

        }

        /// <summary>
        /// 添加API服务(指定Assembly)
        /// </summary>
        /// <param name="services"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public static IServiceCollection AddAPIServices(this IServiceCollection services, Assembly entry)
        {
            Type[] classes = entry.GetTypes();
            foreach (var item in classes)
            {
                if (item.IsInterface) continue;
                if (item.GetInterfaces().Any())
                {
                    foreach (var face in item.GetInterfaces())
                    {
                        if (face.GetInterface(nameof(IAPIService)) != null)
                            services.AddScoped(face, item);
                    }
                }
            }
            return services;
        }
    }
}
